/* 
* @Author: obsidian
* @Date:   2015-12-15 19:59:08
* @Last Modified by:   obsidian
* @Last Modified time: 2016-04-02 08:56:17
*/

#include "gpsteer.h"
#include "gpsteer_driver.h"
#include "driver/sd/file.h"
#include "control/car.h"
#include "module/GPS/GPS.h"
#include "module/brake/brake.h"



static void gpsteer_release(void);
static void gpsteer_init(void);
static void gpsteer_save(void);
static void gpsteer_hold(void);
static void gpsteer_read_sd(void);
void gpsteer_control();

struct Gpsteer gpsteer =
{
    .CCRx          =   (unsigned short *)&TIM2->CCR4,         //CCRx
    .status        =   0,                                     //status
    .midvalue0      =   1170,                                  //midvalue
    .limit         =   {1600, 130},                            //limit
    .ratio         =   2.0,                                   //set_angle
    .init          =   gpsteer_init,                     //
    .read_from_sd  =   gpsteer_read_sd,
    .hold          =   gpsteer_hold,
    .release       =   gpsteer_release,
    .save          =   gpsteer_save,
	.control	   =   gpsteer_control,
};

void gpsteer_control()
{

}


void gpsteer_release()
{
	if(gps.direction == 0)//右边
		*gpsteer.CCRx = gpsteer.limit[0]; 
	else
		*gpsteer.CCRx = gpsteer.limit[1]; 	
}

void gpsteer_hold()
{
	if(gps.direction == 0)//右边
		*gpsteer.CCRx = gpsteer.midvalue0;             
	else//左边
		*gpsteer.CCRx = gpsteer.midvalue1;
}


struct Gpsteer  dup_gpsteer;

/*
	初始化
*/
void gpsteer_init()
{
    TIM_DeInit(TIM2);
    //TIM2_Mode_Config();
}

void gpsteer_read_sd()
{
    unsigned int k = 0;
    
    car.strjoint("gpsteer");
    f_open(&fil,car.path,FA_READ);
    if(fil.fs != 0)
    {
        f_read(&fil, (char *)&dup_gpsteer, sizeof(struct Gpsteer), &k);
        //gpsteer.midvalue = dup_gpsteer.midvalue;
        gpsteer.limit[0] = dup_gpsteer.limit[0];
        gpsteer.limit[1] = dup_gpsteer.limit[1];
        file_close();
    }    
}

void gpsteer_save()
{
    unsigned int k = 0;
    car.strjoint("gpsteer");
    f_open(&fil,car.path,FA_WRITE | FA_CREATE_ALWAYS);
    if(fil.fs == 0){return;}
    f_write(&fil, (char *)&gpsteer, sizeof(struct Gpsteer), &k);
    file_close();
}
